package com.goudan.demo.config;

import com.goudan.demo.common.errorCode.CommonErrorCode;
import com.goudan.demo.common.pojo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

@Slf4j
@RestControllerAdvice("com.goudan.demo.controller")
public class WebGlobalExceptionHandler {
    /**
     * 参数校验异常处理器
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult bindException(MethodArgumentNotValidException e) {
        log.info("进去全局异常处理器,异常信息：{}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        return CommonResult.error(CommonErrorCode.SYS_ERROR.code(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
    }
}
